from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
import jwt
from django.conf import settings
from jwt import exceptions
from home import models #模型类

class MyJWTAuthentication(BaseAuthentication):
    def authenticate(self,request):
        #获取token
        token = request.META.get("HTTP_TOKNE") #从请求头中获取
        if not token:
            token = request.COOKIES.get('token') #从cookies中获取token
        if not token:
            msg = '没有携带token'
            raise AuthenticationFailed({'code': 400, 'msg': msg})
        '''
        1、切割
        2、解密第二段/判断过期
        3、验证第三段合法性
        '''
        #导入settings中的字符串做盐
        salt =settings.SECRET_KEY
        payload = None
        msg = None
        try:
            payload = jwt.decode(token,salt,True)
            user = models.UserModel.objects.filter(id=payload.get('user_id')).first()
            return (user,token)
            #payload={'user_id':user.id}
        except exceptions.ExpiredSignatureError:
            msg='token过期了'
            raise AuthenticationFailed({'code':400,'msg':msg})
        except exceptions.DecodeError:
            msg='token认证失败'
            raise AuthenticationFailed({'code':400,'msg':msg})
        except exceptions.InvalidTokenError:
            msg='非法的token'
            raise AuthenticationFailed({'code':400,'msg':msg})